﻿using cn.Ysserver.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ys4GClient
{
    class TcpSerVice
    {
        int tcp_Port;
        private Boolean tcpLife = true; // udp生命线程
        TcpDataInterface tcpDataInterface;
        String topic;
        public long data_get = 0;
        public long data_send = 0;

        //监听函数，用来接收消息
        private bool tcp_thread_run = true;
        private IPAddress serverIP = null;
        Dictionary<String, TcpClient> dict_client = new Dictionary<String, TcpClient>();//存放套接字
        Dictionary<String, Thread> dict_Thread = new Dictionary<String, Thread>();//存放线程
        // 已接受的Tcp连接列表  
        Thread myThead = null;
        TcpListener server = null;
        public TcpSerVice(int port, String topic)
        {
            this.tcp_Port = port;
            this.topic = topic;
        }
        public void BeginListen()
        {
            tcp_thread_run = true;
            // Buffer for reading data
            while (tcpLife)
            {
                //blocks until a client has connected to the server
                TcpClient client = this.server.AcceptTcpClient();
                //create a thread to handle communication
                //with connected client
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
                dict_client.Add(client.Client.RemoteEndPoint.ToString(), client);
                dict_Thread.Add(client.Client.RemoteEndPoint.ToString(), clientThread);
            }
        }


        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[1024];
            int bytesRead;
            while (tcpLife)
            {
                bytesRead = 0;
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 1024);
                    if (bytesRead > 0)
                    {
                        data_get += bytesRead;
                        byte[] data = new byte[bytesRead];
                         Array.Copy(message, data, bytesRead);
                        tcpDataInterface.onDataReceived(data, topic);
                    }
                    else
                    {
                        break;
                    }
                }
                catch
                {
                    //a socket error has occured
                    break;
                }
            }
            try
            {
                dict_client.Remove(tcpClient.Client.RemoteEndPoint.ToString());
                dict_Thread.Remove(tcpClient.Client.RemoteEndPoint.ToString());
                tcpClient.Close();
            }
            catch
            { }
        }
        public void tcp_send(byte[] data)
        {
            try
            {
                foreach (var client in dict_client)
                {
                    NetworkStream clientStream = client.Value.GetStream();
                    clientStream.Write(data, 0, data.Length);
                }
                data_send += data.Length;
            }
            catch
            { }
        }
        public void stop_tcpservice()
        {
            foreach (var client in dict_client)
            {
                try
                {
                    client.Value.Close();
                }
                catch { }
            }
            foreach (var thread in dict_Thread)
            {
                try
                {
                    thread.Value.Abort();
                }
                catch { }
            }
            dict_client.Clear();
            dict_Thread.Clear();
            server.Stop();
            tcpLife = false;
        }
    }
}
